<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <searchBar :show-channel-id="false" :show-server-id="false" @transferFilter="handleFilter" />
      <el-button v-if="checkPermission(permissionRoles.channel_package_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加渠道包</el-button>
      <el-button class="filter-item" type="success" @click="handleDefault('default_agreement')">默认用户协议</el-button>
      <el-button class="filter-item" type="primary" @click="handleDefault('default_privacy')">默认隐私政策</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border height="725">
      <el-table-column prop="cpid" align="center" label="发行渠道ID"></el-table-column>
      <el-table-column prop="cpname" align="center" label="发行渠道名称"></el-table-column>
      <el-table-column prop="cname" align="center" label="所属渠道"></el-table-column>
      <el-table-column prop="cid" align="center" label="所属渠道ID"></el-table-column>
      <el-table-column prop="srid" align="center" label="指定大区"></el-table-column>
      <el-table-column prop="channel_id" align="center" label="渠道方平台ID"></el-table-column>
      <el-table-column align="center" label="适龄提示" width="80px">
        <template slot-scope="{row}">
          <el-tag v-if="row.age_tips === '0'" type="danger">否</el-tag>
          <el-tag v-else type="success">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="250px" label="版权信息">
        <template slot-scope="{row}">
          <el-tag v-if="row.copyright === null" class="wb"></el-tag>
          <el-tag v-else-if="row.copyright.length < 25">{{ row.copyright }}</el-tag>
          <el-popover v-else trigger="hover" placement="top">
            <p>{{ row.copyright }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ row.copyright | sliceFilter }}</el-tag>
            </div>
          </el-popover>
        </template>

      </el-table-column>
      <el-table-column align="center" label="协议显示" width="80px">
        <template slot-scope="{row}">
          <el-tag v-if="row.is_show_agreement === '0'" type="danger">否</el-tag>
          <el-tag v-else type="success">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="用户协议">
        <template slot-scope="{row}">
          <el-button type="primary" size="small" @click="handleInfo(row, 'agreement')">详情</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="隐私政策">
        <template slot-scope="{row}">
          <el-button type="primary" size="small" @click="handleInfo(row, 'privacy')">详情</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(permissionRoles.channel_package_edit)" type="text" size="small" @click="handleEdit(scope)">修改</el-button>
          <el-button v-if="checkPermission(permissionRoles.channel_package_del)" type="text" size="small" title="删除" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="120px" label-position="left">
        <el-form-item label="发行渠道ID" prop="cpid">
          <el-input v-model="dataForm.cpid" class="defaut-input" placeholder="填写发行渠道ID" />
        </el-form-item>
        <el-form-item label="发行渠道名称" prop="cpname">
          <el-input v-model="dataForm.cpname" class="defaut-input" placeholder="填写发行渠道名称" />
        </el-form-item>
        <el-form-item label="所属渠道" prop="cid">
          <el-select v-model="dataForm.cid" class="defaut-input" filterable clearable multiple>
            <el-option
              v-for="item in channelList"
              :key="item.id"
              :label="item.name"
              :value="item.cid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="指定大区" prop="srid">
          <el-input v-model="dataForm.srid" class="defaut-input" placeholder="格式为:3,10;4,10" />
        </el-form-item>
        <el-form-item label="渠道方平台ID">
          <el-input v-model="dataForm.channel_id" class="defaut-input" placeholder="" />
        </el-form-item>
        <el-form-item label="适龄提示" prop="age_tips">
          <el-switch v-model="dataForm.age_tips" active-value="1" inactive-value="0" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>

        <el-form-item label="版权信息" prop="copyright">
          <el-input v-model="dataForm.copyright" type="textarea" :rows="3" placeholder="请输入内容"></el-input>
        </el-form-item>

        <el-form-item label="协议显示" prop="is_show_agreement">
          <el-switch v-model="dataForm.is_show_agreement" active-value="1" inactive-value="0" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="infoDialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataInfoForm" :model="dataInfoForm" :rules="rules" label-width="120px" label-position="left">
        <el-form-item label="">
          <div v-if="editversion" class="ruleDiv">
            <tinymce v-model="dataInfoForm.content" :height="300" />
          </div>
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="infoDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmInfoSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { objectMerge, deepClone } from '@/utils'
import { getChannelPackageList, handleChannelPackage, deleteChannelPackage, getChannelPackageDefaultContent, getChannelList, handleInfo } from '@/api/ops'
import Pagination from '@/components/Pagination'
import Tinymce from '@/components/Tinymce'
import SearchBar from '@/components/SearchBar'

const defaultItem = {
  id: '',
  cpid: '',
  cpname: '',
  cid: [],
  srid: '',
  channel_id: '',
  age_tips: '0',
  copyright: '',
  is_show_agreement: '0'
}
const infoItem = {
  id: '',
  type: '',
  content: ''
}

export default {
  name: 'ChannelPackage',
  components: { SearchBar, Pagination, Tinymce },
  filters: {
    sliceFilter(str) {
      return str.slice(0, 20)
    }
  },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      total: 0,
      listQuery: {
        page: 1,
        limit: 100
      },
      searchBarQuery: {},
      listLoading: false,
      dataForm: Object.assign({}, defaultItem),
      dataInfoForm: Object.assign({}, infoItem),
      rules: {
        cpid: [{ required: true, message: '请填写发行渠道ID', trigger: 'blur' }],
        cpname: [{ required: true, message: '请填写发行渠道名称', trigger: 'blur' }],
        cid: [{ required: true, message: '请选择所属渠道', trigger: 'blur' }],
        srid: [{ pattern: /^[0-9,;]+$/u, message: '只能包含逗号和分号', trigger: 'blur' }]
      },
      list: [],
      channelList: [],
      dialogVisible: false,
      infoDialogVisible: false,
      infoType: false,
      editversion: false,
      info: '',
      dialogType: 'new',
      textMap: {
        edit: '编辑',
        new: '新增',
        agreement: '用户协议',
        privacy: '隐私政策',
        default_agreement: '默认用户协议',
        default_privacy: '默认隐私政策'
      }
    }
  },
  computed: {
  },
  created() {
    this.init()
    this.getChannelList()
  },
  methods: {
    checkPermission,
    init() {
      this.getList()
    },
    async getChannelList() {
      const res = await getChannelList()
      this.channelList = res.data.items
    },
    handleFilter(query) {
      this.searchBarQuery = query
      this.getList()
    },
    async getList() {
      const query = objectMerge(this.searchBarQuery, this.listQuery)
      this.listLoading = true
      const res = await getChannelPackageList(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
    },
    handleAdd() {
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.dataForm = deepClone(scope.row)
      this.dataForm.cid = this.dataForm.cid.split(',')
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDefault(type) {
      this.dialogType = type
      this.infoType = true
      this.infoDialogVisible = true
      this.editversion = false
      this.dataInfoForm.type = type
      this.getDefaultInfo()
    },
    changeDefault() {
      this.getDefaultInfo()
    },
    getDefaultInfo() {
      getChannelPackageDefaultContent({ type: this.dataInfoForm.type }).then(response => {
        if (response.status) {
          this.editversion = true
          this.dataInfoForm.content = response.data.content
          this.dataInfoForm.id = response.data.id
        }
      })
    },
    handleInfo(row, type) {
      let content = ''
      if (type === 'agreement') content = row.agreement
      if (type === 'privacy') content = row.privacy

      this.infoType = false
      this.dialogType = type
      this.infoDialogVisible = true
      this.dataInfoForm.content = content
      this.dataInfoForm.type = type
      this.dataInfoForm.id = row.id
    },
    handleDelete({ $index, row }) {
      this.$confirm('你确定要删除此列吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteChannelPackage(row.id)
          this.list.splice($index, 1)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          handleChannelPackage(this.dataForm).then(response => {
            if (response.status) {
              if (isEdit) {
                for (let index = 0; index < this.list.length; index++) {
                  if (this.list[index].id === this.dataForm.id) {
                    this.list.splice(index, 1, Object.assign({}, this.dataForm))
                    break
                  }
                }
              } else {
                this.list.push(response.data)
              }
              this.getList()
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    confirmInfoSubmit() {
      handleInfo(this.dataInfoForm).then(response => {
        if (response.status) {
          this.infoDialogVisible = false
          this.getList()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-table {
  font-size: 14px;
}
.el-table td, .el-table th {
  padding: 10px 0;
}
.el-table th>.cell {
  padding-left: 10px;
  padding-right: 10px;
}
.el-table td {
  text-align: left !important;
}

.wb {
  border: 0; background-color: white;
}

</style>
